<!--  -->
<template>
  <div class="wrap">
    <div class="divsearch">
    <input class="search" v-model="searchval" v-on:keyup.enter="search()" placeholder="请输入关键词" />
    </div>
    <div class="chart">
      <div id="container" class="chart1"></div>
    </div>
  </div>
</template>

<script>
import G6 from "@antv/g6";
import axios from "axios";
export default {
  name: "",
  components: {},
  props: [],
  data() {
    return {
      graph: undefined,
      tooltip:undefined,
      searchval:'成都',
      Colors: { noun: "#588c73", adj: "#f2e394", v: "#d96459", adv: "#f2ae72" },
      datalist: {
        nodes: [],
        // 边集
        edges: [],
      },

      
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // this.init()
   
    this.getdata(this.searchval);
  },
  methods: {

     inittooltip(){
  this.tooltip = new G6.Tooltip({
  offsetX: 10,
  offsetY: 10,
  fixToNode: [1, 0.5],
  // the types of items that allow the tooltip show up
  // 允许出现 tooltip 的 item 类型
  itemTypes: ['node', 'edge'],
  // custom the tooltip's content
  // 自定义 tooltip 内容
  getContent: (e) => {
    const outDiv = document.createElement('div');
    outDiv.style.width = 'fit-content';
    outDiv.style.height = 'fit-content';
    const model = e.item.getModel();
    if (e.item.getType() === 'node') {
      outDiv.innerHTML = `${model.name}`;
    } else {
      const source = e.item.getSource();
      const target = e.item.getTarget();
      outDiv.innerHTML = `来源：${source.getModel().name}<br/>去向：${target.getModel().name}`;
    }
    return outDiv;
  },
});
     },
    async getdata(searchval) {
      const container = document.getElementById("container");
      const width = container.scrollWidth;
      const height = container.scrollHeight || 900;
     // this.inittooltip()
      this.graph = new G6.Graph({
        container: "container",
        width: width,
        height: height,
        // fitView: true,
        layout: {
          type: "force",
          linkDistance: 250, // 可选，边长
          nodeStrength: 30, // 可选
          // edgeStrength: 0.1, // 可选
          //nodeSize: 40, // 可选
          preventOverlap: true,
          edgeStrength: 0.7
        },
        // plugins: [this.tooltip],
        defaultNode: {
          size: 50,
          labelCfg: {
            // 节点上的标签文本样式配置
            style: {
              fill: "#fff", // 节点标签文字颜色
              fontSize: 10,
            },
          },
        },
        defaultEdge: {
          // ...                 // 边的其他配置
          // 边样式配置
          style: {
            //opacity: 0.6, // 边透明度
            // stroke: 'grey', // 边描边颜色
            //  endArrow: true,
          },
          // 边上的标签文本配置
          labelCfg: {
            autoRotate: true, // 边上的标签文本根据边的方向旋转
            style: {
              //opacity: 0.6, // 边透明度
              // stroke: 'grey', // 边描边颜色
              fontSize: 10,
              fill: "#fff",
            },
          },
        },
      
        // 内置交互
        modes: {
          default: ["drag-canvas", "zoom-canvas", "drag-node"],
        },
      });
      // var bb = await axios.get(
      //   "https://gw.alipayobjects.com/os/basement_prod/6cae02ab-4c29-44b2-b1fd-4005688febcb.json"
      // );
      var cc = await axios.get(
        "https://api.ownthink.com/kg/knowledge?entity="+searchval
      );
      //this.datalist=bb.data;
      console.log("3333", cc.data.data.avp);

      var dd = cc.data.data.avp;
      for (let i = 0; i < dd.length; i++) {
        var ee = {
          id: dd[i][1],
          label: dd[i][1],
        };

        var ff = {
          source: dd[i][1],
          target: searchval,
          label: dd[i][0],
        };
        this.datalist.nodes.push(ee);
        this.datalist.edges.push(ff);
      }
      this.datalist.nodes.push({ id: searchval, label: searchval });
      console.log("444", this.datalist);
      this.graph.data(this.datalist); // 读取 Step 2 中的数据源到图上
      this.datalist.nodes.forEach((i) => {
        i.style = {
          fill: this.randomColor(),
        };
      });
      this.graph.render(); // 渲染图
      // 监听鼠标进入节点
      this.graph.on("node:dragstart",  (e) =>{
          this.graph.layout();
        refreshDragedNodePosition(e);
      });
        this.graph.on("node:drag", (e) =>{
        const forceLayout = this.graph.get("layoutController").layoutMethods[0];
        forceLayout.execute();
        refreshDragedNodePosition(e);
      });
        this.graph.on("node:dragend",  (e) =>{
        e.item.get("model").fx = null;
        e.item.get("model").fy = null;
      });

      if (typeof window !== 'undefined')
        window.onresize = () => {
          if (!this.graph ||this.graph.get('destroyed')) return;
          if (!container || !container.scrollWidth || !container.scrollHeight) return;
          this.graph.changeSize(container.scrollWidth, container.scrollHeight);
        };
      function refreshDragedNodePosition(e) {
        const model = e.item.get("model");
        model.fx = e.x;
        model.fy = e.y;
      }

// 鼠标进入节点
this.graph.on('node:mouseenter', (e) => {
    const nodeItem = e.item // 获取鼠标进入的节点元素对象
    console.log('鼠标移入', nodeItem._cfg)
})
// 单击节点
this.graph.on('node:click', (e) => {
    const nodeItem = e.item // 获取被点击的节点元素对象
    console.log('单击', nodeItem._cfg)
})
// 双击节点
this.graph.on('node:dblclick', (e) => {
    const nodeItem = e.item // 获取被点击的节点元素对象
    console.log('双击', nodeItem._cfg.id)
    this.search1(nodeItem._cfg.id)
})
    },

    randomColor() {
        const colors = [
          "#F4AB87",
          "#EEC88D",
          "#76CADF",
          "#97DA9D",
          "#88DCD8",
          "#FB7F89",
          "#F0E403",
          "#F576BE",
          "#ACADFF",
          "#7EC3FB",
          "#D0DB02",
          "#C07B11",
          "#00ACC2",
          "#2AAD41",
          "#A59D00",
          "#EB4747",
          "#CD0EBD",
          "#DE3997",
          "#1f77b4",
          "#ff7f0e",
          '#2ca02c',
          '#d62728',
          '#9467bd','#8c564b','#e377c2','#7f7f7f','#bcbd22','#17becf'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
      },

          async search(){
      //alert(111)
     this.datalist.nodes=[];
     this.datalist.edges=[];
       var cc = await axios.get(
        "https://api.ownthink.com/kg/knowledge?entity="+this.searchval
      );
      var dd = cc.data.data.avp;
      for (let i = 0; i < dd.length; i++) {
        var ee = {
          id: dd[i][1],
          label: dd[i][1],
        };

        var ff = {
          source: dd[i][1],
          target: this.searchval,
          label: dd[i][0],
        };
        this.datalist.nodes.push(ee);
        this.datalist.edges.push(ff);
      }
      this.datalist.nodes.push({ id: this.searchval, label: this.searchval });
      console.log("444", this.datalist);
      this.graph.data(this.datalist); // 读取 Step 2 中的数据源到图上
      this.datalist.nodes.forEach((i) => {
        i.style = {
          fill: this.randomColor(),
        };
      });
      this.graph.render(); // 渲染图
      
    },
    async search1(val){
      //alert(111)
    //  this.datalist.nodes=[];
    //  this.datalist.edges=[];
       var cc = await axios.get(
        "https://api.ownthink.com/kg/knowledge?entity="+val
      );
      var dd = cc.data.data.avp;
       if(dd){
      for (let i = 0; i < dd.length; i++) {
        var ee = {
          id: dd[i][1],
          label: dd[i][1],
        };

        var ff = {
          source: dd[i][1],
          target: val,
          label: dd[i][0],
        };
        this.datalist.nodes.push(ee);
        this.datalist.edges.push(ff);
      }
      this.datalist.nodes.push({ id: val, label: val});
      console.log("444", this.datalist);
      this.graph.data(this.datalist); // 读取 Step 2 中的数据源到图上
      this.datalist.nodes.forEach((i) => {
        i.style = {
          fill: this.randomColor(),
        };
      });
      this.graph.render(); // 渲染图
      
    }
  }
  },
};
</script>
<style lang='css'>
*{
      margin: 0;
      padding: 0;
    }
.wrap {
  width: 100%;
  /* position: relative; */
  background-color: #11162a;
}
.divsearch{
  margin: 0 auto;
  text-align: center;
  padding-top: 10px;
}
.wrap .search {
  /* position: absolute;
  left: 50%; */

  width: 640px;
  /* transform: translate(-50%); */
  text-align: center;
  font-size: 18px;
  line-height: 46px;
  border-radius: 100px;
  border: none;
  outline: none;
}

.wrap .chart .chart1 {
  /* position: absolute;  */
  width: 100%;
  height: 100%;
   
}


</style>